package com.jmga.data;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;

public class DataPusherActivity extends Activity {

	public static final Uri CONTENT_URI_PRICES = Uri
			.parse("content://com.jmga.provider.ecogasfinder/price");
	public static final Uri CONTENT_URI_STATIONS = Uri.parse("content://com.jmga.provider.ecogasfinder/station");
	public static final Uri CONTENT_URI_PRICE_TYPES = Uri.parse("content://com.jmga.provider.ecogasfinder/gasType");
	public static final Uri CONTENT_URI_FREQUENCY = Uri.parse("content://com.jmga.provider.ecogasfinder/frequency");

	public static final String KEY_ID = "_id";
	public static final String KEY_DATE = "date";
	public static final String KEY_STATION = "station";
	public static final String KEY_PRICE = "price";
	public static final String KEY_GAS_TYPE = "gasType";
	
	public static final String KEY_DESCRIPTION = "description";
	public static final String KEY_XKEY = "xkey";
	
	public static final String KEY_LABEL = "label";
	public static final String KEY_OPERATOR = "operator";
	public static final String KEY_ADDRESS = "address";
	public static final String KEY_LANE = "lane";
	public static final String KEY_POSTAL_CODE = "postalCode";
	public static final String KEY_PROVINCE = "province";
	public static final String KEY_LOCALITY = "locality";
	public static final String KEY_SALE_TYPE = "saleType";
	public static final String KEY_SENT_TYPE = "sentType";
	public static final String KEY_X_COORD = "Xcoord";
	public static final String KEY_Y_COORD = "Ycoord";
	public static final String KEY_FAVOURITE = "favourite";
	public static final String KEY_REGULAR = "regular";
	public static final String KEY_OBSERVABLE = "observable";
	
	public static final String KEY_TIMES = "times";
	public static final String ROUTE_POINTS = "routePoints";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		ContentResolver cr = getContentResolver();
		final String today = getIntent().getStringExtra("TODAY");
		Log.d(getClass().getName(), "TODAY: " + today);
		
		FileFilter stationsFileFilter = new FileFilter() {
			
			@Override
			public boolean accept(File pathname) {
				return !pathname.getName().startsWith(today) && pathname.getName().contains("station");
			}
		};
		
		FileFilter pricesFileFilter = new FileFilter() {
			
			@Override
			public boolean accept(File pathname) {
				return !pathname.getName().startsWith(today) && pathname.getName().contains("price");
			}
		};
		
		File ecogasFolder = new File("/sdcard/ecogas/");
		File[] stationsFiles = null, pricesFiles = null;
		if(ecogasFolder != null && ecogasFolder.isDirectory()) {
			stationsFiles = ecogasFolder.listFiles(stationsFileFilter);
			Log.d(getClass().getName(), "Encontrados: " + stationsFiles.length + " archivos station");
			pricesFiles = ecogasFolder.listFiles(pricesFileFilter);
			Log.d(getClass().getName(), "Encontrados: " + pricesFiles.length + " archivos prices");
		}
		
		for(File stationFile : stationsFiles) {
			try {
				processStationsCsvFile(stationFile, cr);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		for(File priceFile : pricesFiles) {
			try {
				processPriceCsvFile(priceFile, cr);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}

	private void processStationsCsvFile(File stationFile, ContentResolver cr) throws Exception {
		if(stationFile != null && stationFile.isFile()) {
			  BufferedReader csvFile = 
			        new BufferedReader(new FileReader(stationFile));
			  String dataRow = csvFile.readLine();

			  while (dataRow != null) {
				  if(!dataRow.isEmpty()) {
					  saveGasStation(dataRow);
				  }
				  
				  dataRow = csvFile.readLine();
			  }
			  csvFile.close();
		}
	}
	
	private void saveGasStation(String dataRow) {
		ContentResolver cr = getContentResolver();
		String[] fields = dataRow.split(";");
		
		if(fields.length == 16) {
			String whereStation = GasFinderProvider.KEY_X_COORD + " = '" + fields[11] + "' AND " + GasFinderProvider.KEY_Y_COORD + " = '" + fields[12] + "'";
			ContentValues values = null;
	
			Cursor cursor = cr.query(GasFinderProvider.CONTENT_URI_STATIONS, null,
					whereStation, null, null);
			
			if (cursor.getCount() == 0) {
				values = new ContentValues();
				values.put(GasFinderProvider.KEY_XKEY, fields[1]);
				values.put(GasFinderProvider.KEY_LABEL, fields[2]);
				values.put(GasFinderProvider.KEY_OPERATOR, fields[3]);
				values.put(GasFinderProvider.KEY_ADDRESS, fields[4]);
				values.put(GasFinderProvider.KEY_LANE, fields[5]);
				values.put(GasFinderProvider.KEY_POSTAL_CODE, fields[6]);
				values.put(GasFinderProvider.KEY_PROVINCE, fields[7]);
				values.put(GasFinderProvider.KEY_LOCALITY, fields[8]);
				values.put(GasFinderProvider.KEY_SALE_TYPE,	fields[9]);
				values.put(GasFinderProvider.KEY_SENT_TYPE, fields[10]);
				values.put(GasFinderProvider.KEY_X_COORD, Double.parseDouble(fields[11]));
				values.put(GasFinderProvider.KEY_Y_COORD, Double.parseDouble(fields[12]));
				// if we're taking it from station db is favourite for sure
				values.put(GasFinderProvider.KEY_FAVOURITE, Integer.valueOf(1));
				
				cr.insert(GasFinderProvider.CONTENT_URI_STATIONS, values);
				Log.d(getClass().getName(), "saveGasStation-Pusher-Data-Inserted:" + fields[1]);
			} 
	
			cursor.close();
		}
	}
	
	private void processPriceCsvFile(File priceFile, ContentResolver cr) throws Exception {
		if(priceFile != null && priceFile.isFile()) {
			BufferedReader csvFile = 
			        new BufferedReader(new FileReader(priceFile));
			  String dataRow = csvFile.readLine();

			  while (dataRow != null) {
				  if(!dataRow.isEmpty()) {
					  savePrice(dataRow);
				  }
				  
				  dataRow = csvFile.readLine();
			  }
			  csvFile.close();
		}
	}
	
	private void savePrice(String dataRow) {
		ContentResolver cr = getContentResolver();
		String[] fields = dataRow.split(";");
		SimpleDateFormat formatoDelTexto = new SimpleDateFormat("dd/MM/yyyy HH:mm");
		
		if(fields.length == 5) {
			Date fecha = null;
			try {
				fecha = formatoDelTexto.parse(fields[1]);
			} catch (ParseException e) {
				e.printStackTrace();
			}

			String whereStation = GasFinderProvider.KEY_DATE + " = '" + fecha.getTime() + "'"
			                    + " AND " + GasFinderProvider.KEY_STATION + " = '" + fields[2] + "'"
			                    + " AND " + GasFinderProvider.KEY_PRICE + " = '" + fields[3] + "'"
								+ " AND " + GasFinderProvider.KEY_GAS_TYPE + " = '" + fields[4] + "'";
			ContentValues values = null;
	
			Cursor cursor = cr.query(GasFinderProvider.CONTENT_URI_PRICES, null,
					whereStation, null, null);
			
			if (cursor.getCount() == 0) {
				values = new ContentValues();
				values.put(GasFinderProvider.KEY_DATE, fecha.getTime());
				values.put(GasFinderProvider.KEY_STATION, fields[2]);
				values.put(GasFinderProvider.KEY_PRICE, fields[3]);
				values.put(GasFinderProvider.KEY_GAS_TYPE, fields[4]);
				
				cr.insert(GasFinderProvider.CONTENT_URI_PRICES, values);
				Log.d(getClass().getName(), "savePrice-Pusher-Data-Inserted:" + dataRow);
			} 
	
			cursor.close();
		}
	}
}